﻿@using EmployeeLeaveSystem.Shared;
@using EmployeeLeaveSystem.Shared.Models;
@inject IMessageService _MessageService;
@inject HttpClient _HttpClient;


<Form Model="addWork"
      Layout="@FormLayout.Vertical"
      OnFinish="UpLoad">
    <FormItem Label="个人信息">
        <p>姓名：@GobalManager.myInfo?.Name</p>
        <p>部门信息：@GobalManager.myInfo?.Department?.Name</p>
    </FormItem>
    <FormItem Label="出勤时间">
        <DatePicker @bind-Value="context.StartTime" ShowTime="@true" />
    </FormItem>
    <FormItem Label="出勤时间">
        <DatePicker @bind-Value="context.EndTime" ShowTime="@true" />
    </FormItem>
    <FormItem Label="选择一个审核人">
        <Select @bind-DataSource="staffInfos"
                TItem="StaffInfo"
                TItemValue="int?"
                @bind-Value="context.AcceptStaffId"
                LabelName="@nameof(Department.Name)"
                ValueName="@nameof(Department.Id)"
                Placeholder="选择一个审核人"
                Loading="@_SelectLoading"
                OnFocus="@SelectFocus">
        </Select>
    </FormItem>
    <FormItem>
        <div> 工作时间长度：@((context.EndTime - context.StartTime).TotalHours)小时</div>
        <div>递交时间：@DateTime.Now</div>
        <div>
            @if (nowRules != null) { // 开始对比工作时间是否有早退和迟到
                bool lateEnter = false, earlyExit = false;
                if (TimeHourMinutesompare(nowRules.StartTime, context.StartTime) == 2) lateEnter = true;
                if (TimeHourMinutesompare(nowRules.EndTime, context.EndTime) == 1) earlyExit = true;
                if (lateEnter == false && earlyExit == false) {
                    <div style="color:green">您的考勤状况正常</div>
                    addWork.workState = WorkState.正常;
                } else if (lateEnter == false && earlyExit == true) {
                    <div style="color:red">您疑似早退</div>
                    addWork.workState = WorkState.早退;
                } else if (lateEnter == true && earlyExit == false) {
                    <div style="color:red">您疑似迟到</div>
                    addWork.workState = WorkState.迟到;
                } else {
                    <div style="color:red">您疑似迟到和早退</div>
                    addWork.workState = WorkState.迟到和早退;
                }
            }
        </div>
    </FormItem>
    <FormItem>
        <Button Block Type="@ButtonType.Primary" HtmlType="submit">
            提交
        </Button>
        </FormItem>
        </Form>
        <Divider />
        @if (nowRules != null) {
    <h4>附件：当前部门（@GobalManager.myInfo?.Department?.Name）所发布的考勤规则</h4>
    <p>@nowRules.Name</p>
    <p>出勤规定时间：@nowRules.StartTime.ToString("hh:mm")</p>
    <p>退勤规定时间：@nowRules.EndTime.ToString("hh:mm")</p>
}


@code {
    [Parameter]
    public int? Id { get; set; }
    AddWork addWork = new();
    NowRules? nowRules;
    protected override async Task OnInitializedAsync() {
        addWork.StartTime = DateTime.Now.AddHours(-3);
        addWork.EndTime = DateTime.Now.AddHours(3);

        // 获取部门的考勤规定
        if (GobalManager.myInfo?.Department?.Id != null) {
            nowRules = await _HttpClient.GetFromJsonAsync<NowRules?>($"api/Work/GetLatestRuleForDepartment?id={GobalManager.myInfo?.Department?.Id}");
        }

        if (Id == null) { // 这是一个新增的记录
            addWork.StaffId = GobalManager.myInfo.Id;
        } else { // 这是一个修改的记录
            try {
                var res = await _HttpClient.GetFromJsonAsync<AddWork?>($"api/Work/GetWorkInfo?id={Id}");
                if (res == null) { _MessageService.Error("加载记录失败了"); } else {
                    addWork = res;
                    _MessageService.Success("记录加载成功");
                }
            }
            catch (Exception ex) {
                _MessageService.Error(ex.Message);
                _MessageService.Error("本条记录数据库查询失败");
            }
        }

        InvokeAsync(StateHasChanged);
    }
    int TimeHourMinutesompare(DateTime t1, DateTime t2) { // 0 t1==t1 | 1 t1>t2 | 2 t1<t2
        if (t1.Hour < t2.Hour) { return 2; } else if (t1.Hour > t2.Hour) { return 1; } else {
            {
                if (t1.Minute < t2.Minute) { return 2; } else if (t1.Minute > t2.Minute) return 1;
                else {
                    return 0;
                }
            }
        }
    }
    async void UpLoad() {
        if (Id == null) { // 这是一条新增记录
            await _HttpClient.PostAsJsonAsync<AddWork>("api/Work/AddWorkInfo", addWork);
            _MessageService.Success("成功递交新的记录");
        } else { // 这是一条Update记录
            await _HttpClient.PostAsJsonAsync<AddWork>("api/Work/UpdateWorkInfo", addWork);
            _MessageService.Success("成功更新记录");
        }
    }
    List<StaffInfo> staffInfos = new();
    bool _SelectLoading = false;
    async void SelectFocus() {
        _SelectLoading = true;
        _MessageService.Info("加载审核人信息中");
        await App._appHandle.GetAllStaffInfos();
        staffInfos.Clear();
        for (int i = 0; i < GobalManager.staffInfos.Count; i++) {
            var infos = GobalManager.staffInfos[i];
            if (GobalManager.staffInfos[i].Type == StaffType.Manager) {
                staffInfos.Add(infos);
            }
        }
        _MessageService.Success("加载完成");
        _SelectLoading = false;
        InvokeAsync(StateHasChanged);
    }
}
